var userInfo = null;
var tokenName = null;

$('#token-list').on('click', 'span', function () {
  $(this).addClass('select-active').siblings().removeClass('select-active');
  tokenName = $(this).html();
})


function signIn () {
  nebPay.simulateCall(dappAddress, "0", "getUserInfo", JSON.stringify([]), {
    listener: function(res) {
      if(res.result == '' && res.execute_err == 'contract check failed') {
          toast('合约检测失败，请检查浏览器钱包插件环境！');
          return;
      }
      
      var info = res.result && JSON.parse(JSON.parse(res.result));
      if (info) {
        userInfo = info;
        renderHTML(info);
        $('#loading').hide();
      }
    }
  })
}

signIn()

function renderHTML (info) {
  var html = '';
  for (var i = 0; i < info.token.length; i++) {
    html += '<span>'+info.token[i].tokenName+'</span>'
  }

  $('#token-list').html(html);
}

$('#create-send').on('click', function () {
  var total = $('#total').val();
  var itemNum = $('#item-num').val();
  if (!total || !itemNum || !tokenName) {
    toast('请填写完整信息');
    return false
  }

  var tokenNum = 0;
  for (var i = 0; i < userInfo.token.length; i++) {
    console.log(userInfo.token[i])
    if (userInfo.token[i].tokenName == tokenName.toUpperCase() && +userInfo.token[i].tokenNum >= total) {
      tokenNum = +userInfo.token[i].tokenNum;
    }
  }
  console.log(total, tokenNum)
  if (total <= tokenNum) {
    nebPay.call(dappAddress, "0", "give", JSON.stringify([tokenName, total, itemNum]), { 
      listener: function(res) {
        toast(res.txhash ? '添加空投成功,请稍等大约30秒去领取空投页面查看...' : '添加空投失败');
      }
    })
  } else {
    toast('余额不足');
  }
})